package api

import (
	"github.com/gin-gonic/gin"
	"net/http"
	"shop/config"
	"shop/config/constant"
	"shop/dao"
	"shop/service"
	"shop/utils/convertutil"
	"shop/utils/result"
	"shop/utils/sessionutil"
	"shop/utils/validateutil"
	"time"
)

// SendPhoneVerifyCode 发送手机验证码
func SendPhoneVerifyCode(ctx *gin.Context) {
	phone := ctx.Query("phone")
	if !validateutil.ValidatePhone(phone) {
		result.RenderResult(ctx, result.Fail("手机格式不正确: "+phone))
		return
	}

	result.RenderResult(ctx, service.SendPhoneVerifyCode(phone, constant.CacheKeyPrefixVerifyCodeUserLogin, 600, 3))
}

// LoginByWeixin 微信登录
func LoginByWeixin(ctx *gin.Context) {
	shopId := convertutil.ParseInt(ctx.GetHeader(constant.ParamHeaderShopId))
	loginType := convertutil.ParseInt(ctx.Query("type"))
	wxCode := ctx.Query("code") // 微信小程序登录时必传
	result.RenderResult(ctx, service.LoginByWeixin(shopId, loginType, wxCode))
}

// GetTokenByState  通过state获取token， 电脑端微信扫码登录时
func GetTokenByState(ctx *gin.Context) {
	result.RenderResult(ctx, result.Ok(dao.GetRedisCli().Get(ctx.Query("state")).Val()))
}

// WeixinH5Auth 微信页面授权成功后的回调, 回调示例: http://xxl.blue/shop-api/auth/login/weixinH5Auth/1/?code=061GAWll2zDVn84qZlll2WY2eO3GAWle&state=123#/
func WeixinH5Auth(ctx *gin.Context) {
	token, err := service.WeixinH5Auth(convertutil.ParseInt(ctx.Param(constant.ParamShopId)), ctx.Query("code"))
	if err != nil {
		result.RenderResult(ctx, result.Fail(err.Error()))
		return
	}

	state := ctx.Query("state")
	if state == "weixin_h5" { // 微信端h5方式直接跳转
		ctx.Redirect(http.StatusMovedPermanently, config.LoginByTokenRedirectUiUrl+token) // 跳转的http状态码必须是300多！，不然panic
		return
	}
	// 扫码登录的方式，前端会主动轮询state对应的token
	if err := dao.GetRedisCli().Set(state, token, time.Duration(60)*time.Second).Err(); err != nil {
		result.RenderResult(ctx, result.Fail("token保存失败: "+err.Error()))
	} else {
		result.RenderResult(ctx, result.Ok(""))
	}
}

// TencentAuth 腾讯授权登录的回调,
// auth_code回调示例1: http://xxl.blue/tencentAuth/1?code=061GAWll2zDVn84qZlll2WY2eO3GAWle&state=123#/
// access_token回调示例2: http://xxl.blue/tencentAuth/1?access_token=FE04*****CCE2&expires_in=7776000&refresh_token=88E4*********BE14
func TencentAuth(c *gin.Context) {
	url, err := service.TencentAuthLogin(convertutil.ParseInt(c.Param(constant.ParamShopId)), c.Query("code"))
	if err != nil {
		result.RenderFail(c, err.Error())
	} else {
		c.Redirect(http.StatusPermanentRedirect, url) // 跳转的http状态码必须是300多！，不然panic
	}
}

// LoginByPhoneAndCode 手机号+验证码登录
func LoginByPhoneAndCode(ctx *gin.Context) {
	code := ctx.Query("code")
	if code == "" {
		result.RenderResult(ctx, result.Fail("验证码不能为空"))
		return
	}
	phone := ctx.Query("phone")
	if !validateutil.ValidatePhone(phone) {
		result.RenderResult(ctx, result.Fail("手机格式不正确"))
		return
	}
	result.RenderResult(ctx, service.LoginByPhoneAndCode(convertutil.ParseInt(ctx.GetHeader(constant.ParamHeaderShopId)), phone, code))
}

func Logout(ctx *gin.Context) {
	sessionutil.Logout(sessionutil.GetUserIdFromCtx(ctx))
	result.RenderResult(ctx, result.Ok(nil))
}
